import pygame
import sys
import threading
import serial
import serial.tools.list_ports



def ask_for_port():
    options = serial.tools.list_ports.comports()
    for k, i in enumerate(options):
        print(f"{k}: {i.description}")
    if options:
        port_num = int(input("Choose a port: "))
        port = options[port_num].device
        return port
    else:
        raise Exception("没有检测到串口")

try:
    Ser = serial.Serial()
    Ser.baudrate = 115200
    Ser.port = ask_for_port() 
    Ser.timeout = 5
    Ser.open()
except Exception as e:
    input(f"机器人启动失败, 可能是未检测到串口连接.错误信息：\n{e}")
    exit()


# 磁铁的管脚代号
pins = [4,5,6,7,0,1,2,3]

# 初始化Pygame
pygame.init()

# 设置窗口大小
window_size = (800, 600)
screen = pygame.display.set_mode(window_size)

# 设置颜色
red = (255, 0, 0)
green = (0, 255, 0)

# 设置圆球的半径和位置
radius = 50
positions = [
    (100, 100),
    (200, 100),
    (300, 100),
    (400, 100),
    (100, 300),
    (200, 300),
    (300, 300),
    (400, 300)
]

# 设置8个圆球的状态，默认为红色
circles = [red] * 8

# 设置字体和字号
font = pygame.font.SysFont(None, 30)

UDP_MSG = "Wait For MSG"

# 监听UDP数据包的线程函数
def listen_thread():
    global UDP_MSG, Ser
    while True:
        # 从UDP套接字接收数据
        text =Ser.readline()
        try:
            _data = text.decode()
        except Exception as e:
            _data = str(e)
        if _data:
            UDP_MSG = "Received packet from {}  :{}".format(Ser.port, _data)
            print("\nReceived packet from {}:\n{}\n".format(Ser.port, _data), end="")

threading.Thread(target=listen_thread).start()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # 获取鼠标点击位置
            mouse_x, mouse_y = pygame.mouse.get_pos()
            # 检查是否点击到了圆球
            for i, (x, y) in enumerate(positions):
                if (mouse_x - x)**2 + (mouse_y - y)**2 < radius**2:
                    # 点击后切换圆球颜色
                    if circles[i] == red:
                        circles[i] = green
                        Ser.write(f":{pins[i]} 1\n".encode())
                    else:
                        circles[i] = red
                        Ser.write(f":{pins[i]} 0\n".encode())

    # 清空屏幕
    screen.fill((255, 255, 255))

    # 绘制8个圆球和其中的数字
    for i, (x, y) in enumerate(positions):
        pygame.draw.circle(screen, circles[i], (x, y), radius)
        text_surface = font.render(str(i), True, (0, 0, 0))
        text_rect = text_surface.get_rect(center=(x, y))
        screen.blit(text_surface, text_rect)
    
    text_surface = font.render(UDP_MSG, True, (0, 0, 0))
    text_rect = text_surface.get_rect(center=(300, 400))
    
    screen.blit(text_surface, text_rect)
    # 更新显示
    pygame.display.flip()